package kr.hkit.powerjava.chapter24.work;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import javax.imageio.stream.FileImageInputStream;

public class StudentDao implements InterfaceDao<Student> {
	private ArrayList<Student> lists;
	private static String FILE_NAME= "studenList.data";
	@Override
	public void insertItem(Student item) {
		if(!lists.contains(item)){
			lists.add(item);
		}else{
			System.out.println("중복된 데이터");
		}

	}

	@Override
	public void deleteItem(Student item) {//idx는 삭제할 학번
		//ArrayList 저장된 순서번호 삭제
		lists.remove(item);
		}



	@Override
	public void updateItem(Student item) {
		lists.set(lists.indexOf(item), item);

	}

	@Override
	public Student searchItem(Student item) {
		return lists.get(lists.indexOf(item));
	}

	@Override
	public void prnItemList(Comparator<Student> comp) {
		if (comp == null){
			Collections.sort(lists);
			
		}else{
			Collections.sort(lists, comp);
		}
		for(Student std:lists){
			System.out.println(std);
		}

	}

	@Override
	public void loadFile() {
		ObjectInputStream ois = null;
		try{
			ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(StudentDao.FILE_NAME)));
			lists= (ArrayList<Student>) ois.readObject();
		}catch(FileNotFoundException e){
			try{
				new File(StudentDao.FILE_NAME).createNewFile();
				lists = new ArrayList<>();
			}catch(IOException e1){}
				
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(ois !=null)try{ois.close();}catch(Exception e){}
		}
	}

	@Override
	public void saveFile() {
		ObjectOutputStream oos= null;
		try{
			oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(StudentDao.FILE_NAME)));
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(oos !=null)try{oos.close();}catch(Exception e){}
		}
		
	}

}
